package com.tanhua.manage.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.manage.enums.CommentType;
import com.tanhua.manage.pojo.Comment;
import com.tanhua.manage.pojo.Video;
import com.tanhua.manage.vo.PageResult;
import com.tanhua.manage.vo.VideoPageVo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoPageServiceImpl {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public PageResult queryVideoVoList(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {

        PageResult pageResult = new PageResult();
        List<VideoPageVo> videoPageVoList = new ArrayList<>();
        try {
            com.tanhua.dubbo.server.vo.PageInfo<Video> pageInfo = this.queryVideoList(userId, page, pageSize, sortProp, sortOrder);
            pageResult.setCounts(pageInfo.getTotal());
            pageResult.setPage(pageInfo.getPageNum());
            pageResult.setPagesize(pageInfo.getPageSize());

            List<Video> records = pageInfo.getRecords();
            for (Video record : records) {

                VideoPageVo videoPageVo = new VideoPageVo();
                videoPageVo.setId(record.getId().toHexString());
                videoPageVo.setUserId(record.getUserId());
                videoPageVo.setCreateDate(record.getCreated());
                videoPageVo.setVideoUrl(record.getVideoUrl());
                videoPageVo.setPicUrl(record.getPicUrl());

                //获取nickName
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_Id",record.getUserId());
                UserInfo userInfo = userInfoMapper.selectOne(wrapper);
                videoPageVo.setNickname(userInfo.getNickName());

                //获取点赞数
                Long likeCount = this.queryCommentCount(record.getId().toHexString(), CommentType.LIKE);
                videoPageVo.setLikeCount(Integer.valueOf(String.valueOf(likeCount)));
                //获取评论数
                Long commentCount = this.queryCommentCount(record.getId().toHexString(), CommentType.COMMENT);
                videoPageVo.setCommentCount(Integer.valueOf(String.valueOf(commentCount)));

                videoPageVoList.add(videoPageVo);
            }
        } catch (Exception e) {
            log.error("分页赋值时失败",e);
        }
        Integer pages = (int) (Math.ceil((double)pageResult.getCounts()/pageResult.getPagesize()));

        pageResult.setItems(videoPageVoList);
        pageResult.setPages(pages);
        return pageResult;
    }


    /**
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    private com.tanhua.dubbo.server.vo.PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder){

        com.tanhua.dubbo.server.vo.PageInfo<Video> pageInfo = null;
        try {
            pageInfo = new PageInfo<>();
            pageInfo.setPageNum(page);
            pageInfo.setPageSize(pageSize);

            Query query = Query.query(Criteria.where("userId").is(userId));
            if (StrUtil.equals("descending",sortOrder)){
                PageRequest pageRequest = PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc(sortProp)) );
                query.with(pageRequest);
            } else {
                PageRequest pageRequest = PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.asc(sortProp)));
                query.with(pageRequest);
            }

            List<Video> videoList = mongoTemplate.find(query, Video.class);
            //视频为空
            if (CollUtil.isEmpty(videoList)){
                return pageInfo;
            }

            pageInfo.setTotal(videoList.size());
            pageInfo.setRecords(videoList);
        } catch (Exception e) {
            log.error("分页视频失败",e);
        }
        return pageInfo;
    }

    /**
     * 查询数量
     *
     * @param publishUserId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishUserId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishUserId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);
    }

}
